package top.shaozuo.simple.configuration.microprofile.config.source.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

/**
 * 启动阶段 加载配置信心
 * 
 * @author shaozuo
 *
 */
public class ServletConfigContextListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("初始化ServletConfigContextListener");
		ServletContext servletContext = sce.getServletContext();
		// 获取当前 ClassLoader
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		// get access to the Config instance

		ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
		ConfigBuilder configBuilder = configProviderResolver.getBuilder();
		// 配置 ClassLoader
		configBuilder.forClassLoader(classLoader);
		// 默认配置源（内建的，静态的）
		configBuilder.addDefaultSources();
		// 通过发现配置源（动态的）
		configBuilder.addDiscoveredConverters();
		// 增加扩展配置源（基于 Servlet 引擎）
		// configBuilder.withSources(servletContextConfigSource);
		// 获取 Config
		Config config = configBuilder.build();
		// 注册 Config 关联到当前 ClassLoader
		configProviderResolver.registerConfig(config, classLoader);
		servletContext.setAttribute("microprofile", config);

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// do nothing

	}

}
